package com.lanswon.qzsmk.util.inventoryUtil;

import org.junit.Test;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.lanswon.qzsmk.dao.StorageDetailMapper;
import com.lanswon.qzsmk.dao.StorageRegMapper;
import com.lanswon.qzsmk.model.StorageDetail;

import ch.qos.logback.classic.Logger;

@Component
public class GetInventoryRecordNoUtil {
	
	private static Logger logger = (Logger) LoggerFactory.getLogger(GetInventoryRecordNoUtil.class);
	@Autowired
	StorageRegMapper srm;
	@Autowired
	StorageDetailMapper sdm;
	@Autowired
	DateAndStampUtil dateUtil;
	

	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)
	public String getStorageNo(){
		logger.info("getStorageNo########start");
		//1.获取入库单号
		//查询出库库表中的数据，取最大值+1
		String storageNo = null;
		//数据库中现存的最大单号
		String currentMaxNo = srm.queryStorageNo();
		if("".equals(currentMaxNo)||currentMaxNo==null){
			return "KC00000001";
		}
		logger.debug("currentMaxNo==>"+currentMaxNo);
		Integer no = Integer.parseInt(currentMaxNo.substring(2))+1;
		logger.debug("no==>"+no);
		//取得的数字的长度
		int numLength = String.valueOf(no).length();
		logger.debug("numLength==>"+numLength);
		//判断取得的数字长度与字段长度，如果小于字段长度，那么说明字段的数字位是以0开头的，需要补位
		int addZero = currentMaxNo.substring(2).length()-numLength;
		logger.debug("addZero==>"+addZero);
		if(addZero>0){
			int len = currentMaxNo.substring(2).length();
			storageNo = "KC"+String.format("%0" + len + "d", no);
		}
		if(addZero==0){
			storageNo = "KC"+no;
		}
		logger.debug("库存出入库登记号是==>"+storageNo);
		logger.info("getStorageNo########end");
		return storageNo;
	}
	
	/**
	 * 获取新的配送任务号
	 * @return
	 */
	@Transactional(rollbackFor=Exception.class,propagation=Propagation.REQUIRED)
	public String getDistributeTaskNo() {
		logger.info("getDistributeTaskNo########start");
		String maxDistributeTaskNo = sdm.queryMaxStorageDistributeTaskNo();
		String curDate = dateUtil.getCurrentDate().substring(2);
		if("".equals(maxDistributeTaskNo)||maxDistributeTaskNo==null){
			maxDistributeTaskNo = "P"+curDate+"001";
		}else{
			String distributeDate = maxDistributeTaskNo.substring(1, 7);
			logger.debug("distributeDate==>"+distributeDate);
			if(Integer.parseInt(distributeDate)<Integer.parseInt(curDate)){
				maxDistributeTaskNo = "P"+curDate+"001";
			}
			if(Integer.parseInt(distributeDate)==Integer.parseInt(curDate)){
				maxDistributeTaskNo = "P"+(Integer.parseInt(maxDistributeTaskNo.substring(1))+1);
			}
		}
		logger.debug("配送任务号是===>"+maxDistributeTaskNo);
		logger.info("getDistributeTaskNo########end");
		return maxDistributeTaskNo;
	}

}
